#include "cruncommand.h"
#include <QProcess>
#include <QDebug>
#include <QInputDialog>
#include <iostream>
#include <QMessageBox>

using namespace std;

CRunCommand::CRunCommand(QObject *parent) :
    QObject(parent)
{
    pProcess = new QProcess( this );
    pProcess->setEnvironment( QProcess::systemEnvironment () );
}

CRunCommand::~CRunCommand(){
}

bool CRunCommand::runSudoCommand( const QString &command ){

    bool ok = false;
    QString passwd = QInputDialog::getText( 0, tr("Mount Iso passwd dialog"),
                                            tr("Enter your password to perform administrativ tasks"), QLineEdit::Password,
                                            "", &ok);

    if( ok )
    {
        //pProcess->start( "sudo -S mount -o loop  \"/home/flgor/Desktop/Pp.iso\" \"/home/flgor/Videos\"" );
        pProcess->start("sudo -S " + command );

        pProcess->write( QString( passwd + "\n" ).toAscii() );

        if( !pProcess->waitForFinished( 1200 ) ){
            qDebug() << "this processs was a fail";
            pProcess->closeWriteChannel();
            pProcess->close();


            QMessageBox::warning( 0, tr(" Warning "),
                                 tr( "run process failed"),
                                            QMessageBox::Ok );
            return false;
        }


        qDebug() << pProcess->readAllStandardError();
        qDebug() << pProcess->readAllStandardOutput();
        return true;
    }


    return false;
}

void CRunCommand::runCommandDetached( const QString &command ){
    QProcess detProcess;

    detProcess.startDetached( command );
}

QString CRunCommand::runCommand( const QString &command ){
    QProcess *pCommandProcess = new QProcess( this );

    pCommandProcess->start( command );

    if( !pCommandProcess->waitForFinished( 1200 ) ){
        pCommandProcess->close();
        QMessageBox::warning( 0, tr(" Warning "),
                             tr( "run process failed"),
                                        QMessageBox::Ok );
        return "";
    }

    return pCommandProcess->readAllStandardOutput();
}
